package com.heima.comment.service.impl;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import com.heima.aliyun.scan.GreenScan;
import com.heima.aliyun.scan.ScanResult;
import com.heima.comment.service.CommentHotService;
import com.heima.comment.service.CommentService;
import com.heima.common.exception.CustException;
import com.heima.feigns.UserFeign;
import com.heima.model.comment.dtos.CommentDTO;
import com.heima.model.comment.dtos.CommentLikeDTO;
import com.heima.model.comment.dtos.CommentSaveDTO;
import com.heima.model.comment.pojos.ApComment;
import com.heima.model.comment.pojos.ApCommentLike;
import com.heima.model.comment.vos.ApCommentVo;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threadlocal.AppThreadLocalUtils;
import com.heima.model.user.pojos.ApUser;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

@Service
@Slf4j
public class CommentServiceImpl implements CommentService {
    @Autowired
    UserFeign userFeign;
    @Autowired
    GreenScan greenScan;
    @Autowired
    MongoTemplate mongoTemplate;
/*
* 查看评论列表
* */
    @Override
    public ResponseResult findByArticleId(CommentDTO dto) {
        //1. 参数校验
        //   校验文章id
        //   校验size
        if (dto.getMinDate()==null) {
            dto.setMinDate(new Date());
        }
        if (dto.getSize()==null||dto.getSize()<1){
            dto.setSize(10);
        }


        //热点评论
        List<ApComment> list;
        if(dto.getIndex().intValue()==1){
            Query hotQuery = Query.query(Criteria.where("articleId").is(dto.getArticleId()).and("createdTime").lt(dto.getMinDate()).and("flag").is(1))
                    .with(Sort.by(Sort.Direction.DESC, "likes"));

            list = mongoTemplate.find(hotQuery, ApComment.class);

            int size = dto.getSize() - list.size();
            Query query = Query.query(Criteria.where("articleId").is(dto.getArticleId()).and("flag").is(0))
                    .with(Sort.by(Sort.Direction.DESC, "createdTime")).limit(size);

            List<ApComment> commentList = mongoTemplate.find(query, ApComment.class);

            list.addAll(commentList);
        }else {
            //1. 根据条件查询评论列表
            //   (文章id  , 创建时间 小于最小时间 , 截取size条记录 , 创建时间降序)
            Query query = Query.query(Criteria.where("articleId").is(dto.getArticleId()).and("createdTime").lt(dto.getMinDate()).and("flag").is(0))
                    .with(Sort.by(Sort.Direction.DESC, "createdTime")).limit(dto.getSize());

            list = mongoTemplate.find(query, ApComment.class);
        }








        //2. 判断当前用户是否登录
        ApUser user = AppThreadLocalUtils.getUser();
        if(user==null  || CollectionUtils.isEmpty(list)){
            //3. 如果未登录直接返回评论列表
            return ResponseResult.okResult(list);
        }
        //4. 如果登录了 需要检查在当前评论列表中 哪些评论登陆人点赞过
        List<String> idList = list.stream().map(ApComment::getId).collect(Collectors.toList());
        Query query1 = Query.query(Criteria.where("commentId").in(idList).and("authorId").is(user.getId()));
        List<ApCommentLike> apCommentLikes = mongoTemplate.find(query1, ApCommentLike.class);//查询到多有点赞的评论

        List<ApCommentVo > commentVoList =new ArrayList<>();

        List<String> likeCommentIds = apCommentLikes.stream().map(ApCommentLike::getCommentId).distinct().collect(Collectors.toList());

        list.forEach(apComment ->{
                ApCommentVo apCommentVo =new ApCommentVo();
            BeanUtils.copyProperties(apComment,apCommentVo);
                if (likeCommentIds.contains(apComment.getId())){
                    apCommentVo.setOperation((short)0);
                }

                commentVoList.add(apCommentVo);
            }
        );
        //   (将所有ApComment 转成 ApCommentVO , 点过赞的operation设置为0)
        //   推荐实现:
        //   5.1 根据当前列表中评论id  和  登录人id 查询评论点赞表，得到点赞数据
        //                 commentId  in    评论id列表   authorId = 登录人id
        //   5.2 遍历评论列表
        //             将每一个评论  ApComment 转成 ApCommentVO
        //             其中  如果当前评论id在点赞记录中存在  设置operation字段为0  不存在不用做任何处理
        return ResponseResult.okResult(commentVoList);
    }

    /*
* 点赞评论
* */

    @Autowired
    CommentHotService commentHotService;
    /*@Override
    public ResponseResult like(CommentLikeDTO dto) {
        //1. 参数校验
        //   评论id不能为空  operation必须为 0  或  1
        ApUser user = AppThreadLocalUtils.getUser();
        if (user==null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }
        //2. 根据评论id查询评论数据， 为null返回错误信息

        ApComment comment = mongoTemplate.findById(dto.getCommentId(), ApComment.class);
        if(comment==null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        Short operation = dto.getOperation();
        //3. 如果是点赞操作 判断是否已经点赞
        Query query = Query.query(Criteria.where("authorId").is(user.getId()).and("commentId").is(dto.getCommentId()));
        ApCommentLike apCommentLike = mongoTemplate.findOne(query, ApCommentLike.class);
        Integer likes = comment.getLikes();
        Map result =new HashMap<>();
        if (operation==0){//0：点赞
            if(apCommentLike!=null){
                //   点过赞提示 请勿重复点赞
                CustException.cust(AppHttpCodeEnum.DATA_EXIST,"不可以重复点赞");
            }else {
                //   未点过赞   保存点赞信息到mongo
                //   并修改评论信息的点赞数量( + 1)
                ApCommentLike commentLike = new ApCommentLike();
                commentLike.setAuthorId(user.getId());
                commentLike.setCommentId(dto.getCommentId());
                commentLike.setOperation((short)0);
                mongoTemplate.save(commentLike);
                likes+=1;
                comment.setLikes(likes);
                mongoTemplate.save(comment);

                if(comment.getLikes()>=10&& comment.getFlag().shortValue()==0){
                    commentHotService.hotCommentExecutor(comment);
                }
            }
        }else {
            mongoTemplate.remove(apCommentLike);
           likes-=1;
           if(likes<0){
               CustException.cust(AppHttpCodeEnum.SERVER_ERROR);
           }
            comment.setLikes(likes);
            mongoTemplate.save(comment);
            if(comment.getLikes()>=10&& comment.getFlag().shortValue()==0){
                commentHotService.hotCommentExecutor(comment);
            }
        }
        //   点过赞提示 请勿重复点赞

        //4. 如果是取消点赞操作
        //   删除点赞信息
        //
        //       并修改评论信息的点赞数量( - 1) , 要判断下别减成负数
        //
        //1. 返回结果时，需要返回点赞点赞数量  返回的key要求必须是:  likes
        result.put("likes",likes);
        return ResponseResult.okResult(result);
    }*/
    @Autowired
    RedissonClient redisson;

    @Override
    public ResponseResult like(CommentLikeDTO dto) {
        //1.检查参数
        if (dto.getCommentId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //2.判断是否登录
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //3.点赞操作
        RLock rLock = redisson.getLock("likes-lock");
        rLock.lock();
        ApComment apComment;
        try {
            apComment = mongoTemplate.findById(dto.getCommentId(), ApComment.class);
            if (apComment != null && dto.getOperation() == 0) {
                //更新评论的点赞数量
                apComment.setLikes(apComment.getLikes() + 1);
                mongoTemplate.save(apComment);

                //保存 APP评论信息点赞
                ApCommentLike apCommentLike = new ApCommentLike();
                apCommentLike.setAuthorId(user.getId());
                apCommentLike.setCommentId(apComment.getId());
                // apCommentLike.setOperation(dto.getOperation());
                mongoTemplate.save(apCommentLike);
            } else if (apComment != null && dto.getOperation() == 1) {
                //4.取消点赞
                //更新评论的点赞数量
                apComment.setLikes(apComment.getLikes() < 0 ? 0 : apComment.getLikes() - 1);
                mongoTemplate.save(apComment);
                //更新 APP评论信息点赞
                mongoTemplate.remove(Query.query(Criteria.where("authorId").is(user.getId()).and("commentId").is(apComment.getId())), ApCommentLike.class);

            }
        } finally {
            rLock.unlock();
        }
        //5.数据返回
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("likes",apComment.getLikes());
        return ResponseResult.okResult(resultMap);
    }
    /*
    * 保存评论
    * */
    @Override
    public ResponseResult saveComment(CommentSaveDTO dto) {
        //1. 校验参数
        //   校验是否登录
        ApUser user = AppThreadLocalUtils.getUser();
        if(user==null){
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }
        //3. 远程查询当前登陆用户信息
        ResponseResult<ApUser> userResult = userFeign.findUserById(user.getId());
        if (userResult.getCode()!=0){
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR,userResult.getErrorMessage());
        }
        user=userResult.getData();
        if (user==null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //   校验文章id   校验内容不为空  校验内容长度不能大于140个字符 (validated校验)
        //2. 阿里云校验评论内容是否违规
        String content = dto.getContent();
        try {
            ScanResult scanResult = greenScan.greenTextScan(content);
            String filteredContent = scanResult.getFilteredContent();
            if(filteredContent!=null){
                dto.setContent(filteredContent);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        //        过滤掉违规词汇：替换为**
        //4. 创建评论信息，并保存到mongo
        ApComment comment = new ApComment();
        comment.setAuthorId(user.getId());
        comment.setAuthorName(user.getName());
        comment.setArticleId(dto.getArticleId());
        comment.setType((short)0);
        comment.setContent(dto.getContent());
        comment.setImage(user.getImage());
        comment.setLikes(0);
        comment.setReply(0);
        comment.setFlag((short)0);
        comment.setCreatedTime(new Date());
        comment.setUpdatedTime(new Date());

        mongoTemplate.save(comment);
        return ResponseResult.okResult();
    }
}
